package org.jgs1904.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author: 默苍璃
 * @date: 2022-01-04 15:35
 */
public class MybatisUtils {

    public static SqlSessionFactory sqlSessionFactory;

    static {

        String resource = "mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取 SqlSession 连接
     *
     * @return
     */
    public static SqlSession getSession() {
        //开启事务自动提交
        return sqlSessionFactory.openSession(true);
    }


    /**
     * 获取 SqlSession 连接
     *
     * @return
     */
    public static SqlSession getSession(boolean flag) {
        return sqlSessionFactory.openSession(flag);
    }

}
